var soon = {}

soon.loading = function (msg) {

    if (msg == false) {
        $(".loading-mask").remove();
        return;
    }

    if ($(".loading-mask").length == 0) {
        if (msg == undefined) {
            msg = "loading...";
        }
        $("body").append('<div class="loading-mask"> <div class="loading-box"> <div class="loading-animation"></div> <p>' + msg + '</p> </div></div>');
    }
}
soon.ajax = function (settings) {

    settings = $.extend({
        async: true,
        beforeSend: function () { },
        cache: false,
        data: {},
        dataType: "json",
        error: function () { },
        success: function () { },
        type: "post",
        url: "",
        loading: "正在处理",
        errroMsg: "请求失败，服务器繁忙",
        isError: true,
    }, settings || {});

    if (settings.loading != false) {
        soon.loading(settings.loading);
    }

    settings.data._isajax = "false";

    $.ajax({
        async: settings.async,
        beforeSend: settings.beforeSend,
        cache: settings.cache,
        contentType: settings.contentType,
        data: settings.data,
        dataType: settings.dataType,
        error: function (err) {
            setTimeout(function () {
                soon.loading(false);
            }, 100);
            if (settings.isError) {
                layer.msg(settings.errroMsg);
            }
            settings.error(err);
            console.log(err);
        },
        success: function (data, textStatus, jqXHR) {

            setTimeout(function () {
                soon.loading(false);
            }, 100);

            if (data.Action == "Soon.Platform.Timeout") {

                layer.open({
                    title: "登录失效",
                    icon: 2,
                    content: data.Message,
                    btn: ["确认"],
                    closeBtn: false,
                    yes: function (index) {
                        layer.close(index);
                        top.window.location = "/Platform/Quit";
                    }
                });

            } else {

                settings.success(data, textStatus, jqXHR);

            }
        },
        type: settings.type,
        url: settings.url
    });

};
soon.open = function (settings) {

    settings = $.extend({
        url: "",
        data: {},
        id: $.Guid(),
        title: "",
        width: "80%",
        height: "80%",
        iframe: false,
        btn: undefined,
        closeBtn: 1,
        shade: 0.4,
        content: '',
        success: function () {

        }, error: function () {

        }, end: function () {

        }, btn2: function () {

        }, btn2: function () {

        }
    }, settings || {});

    if (settings.iframe == false) {

        var xhhd;

        var inx = layer.open({
            id: settings.id,
            title: settings.title,
            area: [settings.width, settings.height],
            type: 1,
            content: settings.content,
            btn: settings.btn,
            zIndex: 9999,
            closeBtn: settings.closeBtn,
            shade: settings.shade,
            yes: function () {
                settings.success();
            }, end: function () {

                try {
                    if (xhhd) {
                        //销毁后清除无效标签
                        xhhd.each(function () {
                            $(this).data().combo.panel.panel("destroy");
                        });
                    }
                } catch (e) {

                }

                settings.end();

            },
            btn2: settings.btn2,
            btn3: settings.btn3,
        });

        settings.data._openid = inx;

        if (settings.url != undefined && settings.url != "") {

            soon.load({
                url: settings.url,
                data: settings.data,
                type: settings.type,
                loading: "载入页面",
                success: function (data) {
                    $("#" + settings.id).html(data);
                    $.parser.parse($("#" + settings.id))
                    $("#" + settings.id).soon();
                    xhhd = $("#layui-layer" + inx + " .combo-f");
                },
                error: function (data) {
                    var id = "err_" + $.Guid();
                    $("#" + settings.id).html('<iframe scrolling="no" frameborder="0"  id="' + id + '" style="width:99%;height:99%;"></iframe>');
                    $("#" + id).contents().find("html").html(data);
                }
            });

        } else {
            $.parser.parse($("#" + settings.id));
            $("#" + settings.id).soon();
            xhhd = $("#layui-layer" + inx + " .combo-f");
        }

        soon._openid = inx;

        return inx;

    } else {
        var inx = layer.open({
            id: settings.id,
            title: settings.title,
            area: [settings.width, settings.height],
            type: 2,
            content: settings.url,
            btn: settings.btn,
            closeBtn: settings.closeBtn,
            zIndex: 9999,
            yes: function () {
                settings.success();
            },
            end: function () {
                settings.end();
            }
        });
        $.soon._openid = inx;
    }


};
soon.load = function (settings) {

    settings = $.extend({
        url: "",
        loading: "加载中",
        data: {},
        success: function () { },
        error: function () { }
    }, settings || {});

    soon.ajax({
        url: settings.url,
        data: settings.data,
		type: settings.type,
        dataType: 'html',
        isError: false,
        loading: settings.loading,
        success: function (data) {
            soon.loading(false);
            settings.success(data);
        },
        error: function (error) {
            soon.loading(false);
            if (error.status == 404) {
                soon.ajax({
                    url: "/Platform/Error404",
                    dataType: 'html',
                    isError: false,
                    loading: settings.loading,
                    success: function (data) {
                        settings.error(data);
                    }
                });
            } else {
                settings.error(error.responseText);
            }
        }
    });
	
}
soon.treeFilter = function (rows) {

    function exists(rows, _parentId) {
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].id == _parentId) return true;
        }
        return false;
    }

    var nodes = [];
    // 得到顶层节点  
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        if (!exists(rows, row._parentId)) {
            nodes.push(row);
        }
    }

    var toDo = [];
    for (var i = 0; i < nodes.length; i++) {
        toDo.push(nodes[i]);
    }
    while (toDo.length) {
        var node = toDo.shift();    // 父节点   
        // 得到子节点   
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (row._parentId == node.id) {
                if (node.children) {
                    node.children.push(row);
                } else {
                    node.children = [row];
                }
                toDo.push(row);
            }
        }
    }
    return nodes;
};
soon.service = function (settings) {

    if (settings == undefined) {
        settings = {
            url: "/",
            data: "",
            loading: false,
            error: function () {
                layer.open({
                    closeBtn: false,
                    title: "操作失败",
                    btn: ["重新连接"],
                    content: '互助助手连接失败，请检查互助助手是否正常运行',
                    yes: function (index) {
                        layer.close(index);
                        soon.service();
                    }
                })
            },
            success: function () { },
        };
    }

    settings = $.extend({
        url: "/",
        data: "",
        loading: false,
        error: function () { },
        success: function () { },
    }, settings || {});

    if (settings.loading != false) {
        soon.loading(settings.loading);
    }

    $.ajax({
        url: 'http://127.0.0.1:41092' + settings.url,
        data: settings.data,
        type: "post",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (settings.loading != false) {
                soon.loading(false);
            }
            settings.success(data);
        },
        error: function () {
            $.ajax({
                url: 'http://127.0.0.1:26021' + settings.url,
                data: settings.data,
                async: false,
                type: "post",
                dataType: "json",
                cache: false,
                success: function (data) {
                    if (settings.loading != false) {
                        soon.loading(false);
                    }
                    settings.success(data);
                },
                error: function () {
                    $.ajax({
                        url: 'http://127.0.0.1:38401' + settings.url,
                        data: settings.data,
                        async: false,
                        type: "post",
                        dataType: "json",
                        cache: false,
                        success: function (data) {
                            if (settings.loading != false) {
                                soon.loading(false);;
                            }
                            settings.success(data);
                        },
                        error: function () {
                            if (settings.loading != false) {
                                soon.loading(false);
                            }
                            settings.error();
                        }
                    });
                }
            });
        }
    });

};
soon.websocket = function () {

};

(function ($) {

    $.fn.extend({

        //框架组件初始化
        soon: function (command, a, b, c, d, e, f, g) {

            //是否测试组件连接
            var testService = false;


            /*
              ********* 框架组件初始化 *********
             */
            if (command == "listitem") {
                var param = {
                    onClick: function () {

                    },
                    data: []
                };
                param = $.extend(param, a || {});
                var doc = $(this);
                var html = "";
                if (param.data.length == 0) {
                    doc.find("li").each(function () {
                    	if($(this).attr("data-onStep") == $(this).attr("data-id")){
                    		html += "<li class='on'><span>" + $(this).html() + "</span> <span style='float: right;'> <i class=\"fa fa-angle-right \"></i> <input type=\"checkbox\" \ value='" + $(this).attr("data-id") + "'></span> </li>";
                    	}else{
                    		html += "<li><span>" + $(this).html() + "</span> <span style='float: right;'> <i class=\"fa fa-angle-right \"></i> <input type=\"checkbox\" \ value='" + $(this).attr("data-id") + "'></span> </li>";
                    	}
                    	
                    });
                } else {
                    for (var i = 0; i < param.data.length; i++) {
                        html += "<li><span>" + param.data[i].text + "</span> <span style='float: right;'> <i class=\"fa fa-angle-right \"></i> <input type=\"checkbox\" \ value='" + param.data[i].id + "'></span></li>";
                    }
                }

                doc.html(html);

                doc.find("li").click(function () {
                    doc.find("li").removeClass("on");
                    doc.find(":checkbox").prop("checked", false);
                    $(this).addClass("on");
                    param.onClick($(this).find("input[type='checkbox']").prop("checked", true).val());
                });

                if (!doc.hasClass("soon-assembly-listitem")) {
                    doc.addClass("soon-assembly-listitem");
                }

                return;
            }

            /*
                *********  组织机构选择器  *********

                name：name属性
                value：选择值
                title：标题
                range：限定机构范围
                unit：是否允许选择单位 默认允许
                dept：是否允许选择部门 默认允许
                station：是否允许选择岗位 默认允许
                user：是否允许选择人员 默认允许
                more：是否允许多选 默认允许
                online：是否选择在线人员 默认允许
                workgroup：是否选择工作组 默认允许
                role：是否选择角色 默认允许
                disabled：是否禁用
                main：是否只显示主要成员 默认是
                isrequired：是否必选
                mode：显示模式
            */

            var array = new Array();
            if ($(this).hasClass("soon-organize")) {
                array.push(this);
            } else {
                $(this).find(".soon-organize").each(function () {
                    array.push(this);
                });
            }

            $.each(array, function () {

                var $source = $(this);

                //参数
                var range = $source.attr("range") ? $source.attr("range") : "";
                var unit = ($source.attr("unit") == "false" || $source.attr("unit") == "0") ? 0 : 1;
                var dept = ($source.attr("dept") == "false" || $source.attr("dept") == "0") ? 0 : 1;
                var station = ($source.attr("station") == "false" || $source.attr("station") == "0") ? 0 : 1;
                var user = ($source.attr("user") == "false" || $source.attr("user") == "0") ? 0 : 1;
                var workgroup = ($source.attr("workgroup") == "true" || $source.attr("workgroup") == "1") ? 1 : 0;
                var role = ($source.attr("role") == "true" || $source.attr("role") == "1") ? 1 : 0;
                var more = ($source.attr("more") == "false" || $source.attr("more") == "0") ? 0 : 1;
                var main = ($source.attr("main") == "true" || $source.attr("main") == "1") ? 1 : 0;
                var disabled = $source.attr("disabled") == "true" && $source.attr("disabled") == "1" ? 1 : 0;
                var required = ($source.attr("isrequired") == "true" || $source.attr("isrequired") == "1") ? 1 : 0;
                var title = $source.attr("title") ? $source.attr("title") : "";
                var id = $source.attr("id") ? $source.attr("id") : (("i" + $.Guid()));
                var name = $source.attr("name") ? $source.attr("name") : "";
                var className = $source.attr("class").replace("soon-organize", "");
                var value = $source.val() ? $source.val() : "";
                var width = $source.attr("width") ? $source.attr("width") : "";
                var mode = $source.attr("mode") ? $source.attr("mode") : "1";
                var url = "/PlatformAssembly/Organize?range=" + range + "&unit=" + unit + "&dept=" + dept + "&station=" + station + "&user=" + user + "&workgroup=" + workgroup + "&role=" + role + "&main=" + main + "&more=" + more + "&id=" + id;
                var $html_tools = "";
                var $html = "";

                if (mode == "1") {

                    if (disabled == 0) {
                        $html_tools +=
                            '<div class="toolbar">'
                                + '<a class="easyui-linkbutton soon-assembly-organize-add" data-options="plain:true"><i class="fa fa-search "></i>选择</a>'
                                + '<div class="datagrid-btn-separator"></div>'
                                + '<a class="easyui-linkbutton soon-assembly-organize-trash" data-options="plain:true"><i class="fa fa-trash "></i>清空</a>'
                            + '</div>'
                    }
                    $html = '<div id="' + id + '_box" class="soon-assembly-organize ' + className + ' " ' + (width == "" ? "" : ("style='width:" + width + "'")) + ' >'
                                + '<div class="soon-assembly-organize-title"> ' + (title == "" ? "组织机构选择" : title) + '</div> '
                                + $html_tools
                                + '<div id="' + id + '_list_box" style="width:100%"><table id="' + id + '_list" style="width:100%"></table></div>'
                                + '<div class="soon-assembly-organize-null">未选择</div>'
                                + '<div class="soon-assembly-organize-text"><input type="text" id="' + id + '" name="' + name + '" value="' + value + '" ' + (required == 1 ? ' class="easyui-validatebox" data-options="required:true,missingMessage:\'请选择机构\'" ' : '') + ' /></div>'
                             + '</div>';

                } else if (mode == "2") {

                    var $html =
                        '<div id="' + id + '_box" class="soon-assembly-organize-simple " >'
                           + '<input  type="hidden"  id="' + id + '" name="' + name + '" value="' + value + '"  />'
                           + '<input  type="text" id="' + id + '_tag" class="easyui-tagbox ' + className + '" style="width:' + (width == "" ? "300px" : width) + '" ' + (disabled == 1 ? "disabled=disabled" : "") + ' data-options="buttonText: \'  选择 \'" />'
                        + '</div>';

                }

                $(this).before($html);
                $(this).remove();
                $.parser.parse($("#" + id + "_box"));

                var open = function () {

                    var index = $.soon.open({
                        id: "open_" + id,
                        url: url,
                        data: { val: $("#" + id).val() },
                        width: "450px",
                        height: "80%",
                        title: false,
                        closeBtn: 0,
                        btn: ['确认', '取消'],
                        success: function (data) {

                            layer.close(index);

                            var select = [];



                            if ($("#platform_" + id + "_list1").length > 0) {
                                var select1 = $("#platform_" + id + "_list1").treegrid("getSelections");
                                for (var i = 0; i < select1.length; i++) {
                                    select.push(select1[i]);
                                }
                            }
                            if ($("#platform_" + id + "_list2").length > 0) {
                                var select2 = $("#platform_" + id + "_list2").treegrid("getSelections");
                                for (var i = 0; i < select2.length; i++) {
                                    select.push(select2[i]);
                                }
                            }
                            if ($("#platform_" + id + "_list3").length > 0) {
                                var select3 = $("#platform_" + id + "_list3").treegrid("getSelections");
                                for (var i = 0; i < select3.length; i++) {
                                    select.push(select3[i]);
                                }
                            }


                            if (select.length > 0) {

                                var val = "";
                                for (var i = 0; i < select.length; i++) {

                                    var uid = select[i].id;
                                    if (uid.indexOf("_") > -1) {
                                        uid = "u" + uid.split("_")[1];
                                    }

                                    if (val == "") {
                                        val = uid;
                                    } else {
                                        val += "," + uid;
                                    }
                                }

                                $("#" + id).val(val);

                            } else {

                                layer.msg("未选择");
                                $("#" + id).val("");

                            }

                            change();

                        }
                    });

                };
                var change = function () {

                    if (mode == "1") {

                        $("#" + id + "_list").datagrid({
                            url: '/PlatformAssembly/GetOrganizeList?ids=' + $("#" + id).val(),
                            border: false,
                            fitColumns: true,
                            columns: [[
                                {
                                    field: "name",
                                    title: " 名称 ",
                                },
                                {
                                    field: "types",
                                    title: " 类型 ",
                                },
                                {
                                    field: "path",
                                    title: " 所属机构 ",
                                }
                            ]]
                        });


                        if ($("#" + id).val() == "") {
                            $("#" + id + "_box .soon-assembly-organize-null").show();
                        } else {
                            $("#" + id + "_box .soon-assembly-organize-null").hide();
                        }

                    } else if (mode == "2") {

                        var tag = $('#' + id + '_tag');
                        tag.tagbox("clear");
                        if ($("#" + id).val() != "") {
                            $.ajax({
                                url: '/PlatformAssembly/GetOrganizeList?ids=' + $("#" + id).val(),
                                dataType: "json",
                                success: function (data) {
                                    var temp = [];
                                    for (var i = 0; i < data.rows.length; i++) {
                                        var item = data.rows[i];
                                        temp.push(item.name + '<b>' + item.id + '</b>');
                                    }
                                    tag.tagbox("setValues", temp);
                                }
                            });
                        }

                    }



                };

                if (mode == "1") {

                    if (disabled == 0) {
                        $("#" + id + "_box .soon-assembly-organize-add").click(open);
                        $("#" + id + "_box .soon-assembly-organize-trash").click(function () {
                            $("#" + id).val("");
                            change();
                            layer.msg("清空成功");
                        });
                    }

                } else if (mode == "2") {

                    var config = {};

                    if (required == 1) {
                        config.required = true;
                    }

                    if (disabled == 0) {
                        config.buttonText = ' <i class="fa fa-search"><i/> 选择';
                        config.onClickButton = open;
                        config.onRemoveTag = function (val) {

                            var removeId = val.replace("</b>", "").split('<b>')[1];
                            var ids = $("#" + id).val().split(',');
                            var temp = "";
                            for (var i = 0; i < ids.length; i++) {
                                if (ids[i] != removeId) {
                                    temp += (temp == '' ? '' : ',') + ids[i];
                                }
                            }
                            $("#" + id).val(temp);

                        };
                    }

                    $('#' + id + '_tag').tagbox(config);

                }

                change();

            });




            /*
                 *********  图标选择器  *********

                 value: 图标值
                 isrequired：是否必选

            */

            array = new Array();
            if ($(this).hasClass("soon-icon")) {
                array.push(this);
            } else {
                $(this).find(".soon-icon").each(function () {
                    array.push(this);
                });
            }
            $.each(array, function () {

                var $source = $(this);
                var id = $source.attr("id") ? $source.attr("id") : ("i" + $.Guid());
                var name = $source.attr("name") ? $source.attr("name") : id;
                var value = $source.val() ? $source.val() : "";
                var className = $source.attr("class") ? $source.attr("class").replace("soon-icon", "") : "";
                var required = ($source.attr("isrequired") == "false" || $source.attr("isrequired") == "0") ? 0 : 1;

                var html = '<div class="soon-assembly-icon" id="' + id + '_box">';
                html += '<div id="' + id + '_icon" class="soon-assembly-icon-show"><i class="' + value + '"></i><span>' + value.replace(/fa /g, '') + '</span></div>';
                html += '<a class="easyui-linkbutton" id="' + id + '_btn"><i class="fa fa-search "></i> 选择</a>';
                html += '<input type="text" id="' + id + '" name="' + name + '" value="' + value + '" ' + (required == 1 ? ' class="easyui-validatebox" data-options="required:true,missingMessage:\'请选择图标\'" ' : '') + ' />';

                $(this).before(html);
                $(this).remove();
                $.parser.parse($("#" + id + "_box"));

                $("#" + id + "_btn").click(function () {

                    $.soon.open({
                        id: "open_" + id,
                        url: '/PlatformAssembly/Icon?id=' + id,
                        width: $(window).width() * 0.8 + "px",
                        height: $(window).height() * 0.8 + "px",
                        title: "请选择图标"
                    });

                });

                if (value != "") {
                    $("#" + id + "_icon").show();
                } else {
                    $("#" + id + "_icon").hide();
                }

            });


            /*
                 *********  百度编辑器  *********
            */

            array = new Array();
            if ($(this).hasClass("soon-ueditor")) {
                array.push(this);
            } else {
                $(this).find(".soon-ueditor").each(function () {
                    array.push(this);
                });
            }
            $.each(array, function () {
                var name = $(this).attr("name");
                var id = $.Guid();
                var width = "";
                var height = "";
                if ($(this).attr("width")) {
                    width = " width:" + $(this).attr("width") + ";";
                } else {
                    width = " width:100%; "
                }
                if ($(this).attr("height")) {
                    height = " height:" + $(this).attr("height") + ";";
                } else {
                    height = "height:300px;"
                }

                $(this).before('<script id="' + id + '" name="' + name + '" style=" ' + width + ' ' + height + ' " type="text/plain">' + $(this).text() + '</script>');
                $(this).remove();
                var editor = UE.getEditor(id);

            });


            /*
                 *********  封面图片上传插件  *********
            */

            array = new Array();
            if ($(this).hasClass("soon-cover")) {
                array.push(this);
            } else {
                $(this).find(".soon-cover").each(function () {
                    array.push(this);
                });
            }

            $.each(array, function () {

                var $source = $(this);
                var id = $source.attr("id") ? $source.attr("id") : ("i" + $.Guid());
                var path = $source.attr("path") ? $source.attr("path") : "/cover";
                var readonly = ($source.attr("read") == "false" || $source.attr("read") == "0") ? 0 : 1;
                var val = $source.html();
                var required = ($source.attr("isrequired") == "false" || $source.attr("isrequired") == "0") ? 0 : 1;
                var html = '<div id="' + id + '_box" class="soon-assembly-cover">';
                if (readonly == 0) {
                    html += '<a class="easyui-linkbutton" style="position:relative;" id="' + id + '_btn" title="点击上传图片"> <i class="fa fa-image"></i>上传图片</a>  ';
                    html += '<a class="easyui-linkbutton" id="' + id + '_del_btn"> <i class="fa fa-close"></i>删除重传</a>';
                }
                html += '<input type="text" id="' + id + '" name="' + $source.attr("name") + '" value="' + val + '" ' + (required == 1 ? ' class="easyui-validatebox" data-options="required:true,missingMessage:\'请上传图片\'" ' : '') + ' />';
                html += '<input type="file" id="' + id + '_file" style="display:none;" />';
                html += '</div>';
                $source.before(html);
                $source.remove();
                $.parser.parse($("#" + id + "_box"));
                $("#" + id).val(val);

                var getFileURL = function (val) {

                    $.ajax({
                        url: "/PlatformAssembly/GetFileURL",
                        data: { val: val },
                        dataType: "text",
                        success: function (data) {

                            $img = $("#" + id + "_box img");
                            if (!$img.length) {
                                $img = $('<div class="soon-assembly-cover-img"> <img src="' + data + '" /> </div>').prependTo($("#" + id + "_box"));
                                $('#' + id + '_box').viewer({ zIndex: 99999, title: false });
                            } else {
                                $img.attr("src", data);
                            }
                            
                            $("#" + id + "_del_btn").show();

                        }
                    });

                }

                var submitData = function (data, name) {
                    $.soon.ajax({
                        url: "/PlatformAssembly/UploadImageSubmit",
                        data: { data: data, path: path, encrypt: 0, name: name },
                        success: function (response) {
                            if (response.State == true) {
                                $("#" + id).val(response.Data);
                                getFileURL(response.Data);
                            } else {
                                layer.msg("图片上传失败");
                            }
                        }, error: function () {
                            layer.msg("上传失败");
                        }
                    });
                }

                $("#" + id + "_btn").click(function () {

                    var html = '<div style="padding:20px 0; text-align:center;" id="' + id + '_selected">' +
                                    '<a class="layui-btn select-file">选择本地文件</a>' +
                                    '<a class="layui-btn layui-btn-normal">高清拍摄仪</a>' +
                               '</div>';

                    var inx = layer.open({
                        title: "上传方式",
                        area: ["300px", "130px"],
                        type: 1,
                        content: html,
                        zIndex: 9999,
                        success: function () {

                            $("#" + id + "_selected .select-file").click(function () { layer.close(inx); $("#" + id + "_file").click(); });
                            $("#" + id + "_selected .layui-btn-normal").click(function () {
                                layer.close(inx);
                                $.soon.service({
                                    url: '/photo',
                                    loading: "正在处理",
                                    success: function (data) {
                                        if (data.State) {
                                            submitData(data.Data, "Photo.jpg");
                                        }
                                    }, error: function () {
                                        layer.msg('互助助手连接失败!');
                                    }
                                });
                            });
                        }
                    });



                });

                $("#" + id + "_file").on('change', function (e) {

                    var target = $(e.target);
                    var size = target[0].files[0].size / 1024;
                    if (size > 5 * 1024) {
                        layer.msg("图片不能超过5M，请重新选择!");
                        return false;
                    }
                    if (!this.files[0].type.match(/image.*/)) {
                        layer.msg('请选择正确的图片!')
                    } else {
                        var reader = new FileReader();
                        reader.onload = function (evt) {
                            submitData((evt.target.result + "").replace("data:image/jpg;base64,", "").replace("data:image/jpeg;base64,", "").replace("data:image/png;base64,", ""), target[0].files[0].name);
                        }
                        reader.readAsDataURL(target[0].files[0]);
                    }

                });

                if (val != "" && val != undefined) {
                    getFileURL(val);
                }

                $("#" + id + "_del_btn").hide().click(function () {
                    $("#" + id + "_box .soon-assembly-cover-img").remove();
                    $("#" + id).val("");
                    $(this).hide();
                });


            });


            /*
                 *********  地区选择器  *********

                 parentid: 上级地区
                 level: 末级地区等级
                 isrequired：是否必选

            */

            array = new Array();
            if ($(this).hasClass("soon-location")) {
                array.push(this);
            } else {
                $(this).find(".soon-location").each(function () {
                    array.push(this);
                });
            }
            $.each(array, function () {

                var $source = $(this);
                var id = $source.attr("id") ? $source.attr("id") : ("i" + $.Guid());
                var name = $source.attr("name") ? $source.attr("name") : id;
                var value = $source.val() ? $source.val() : "";
                var className = $source.attr("class") ? $source.attr("class").replace("soon-location", "") : "";

                var required = ($source.attr("isrequired") == "false" || $source.attr("isrequired") == "0") ? 0 : 1;
                var parentid = $source.attr("parentid") ? $source.attr("parentid") : "100000";
                var level = $source.attr("level") ? parseInt($source.attr("level")) : 3;

                var html = '<div class="soon-assembly-location ' + className + '" id="' + id + '_box"><div class="soon-assembly-location-select" id="' + id + '_select"></div>';
                html += '<input type="text" id="' + id + '" name="' + $source.attr("name") + '" value="' + value + '" ' + (required == 1 ? ' class="easyui-validatebox" data-options="required:true,missingMessage:\'请选择地区\'" ' : '') + ' />';
                html += '</div>';

                $(this).before(html);
                $(this).remove();

                var assemblyLocation = [];
                var $box = $("#" + id + "_select");
                var ini = true;
                var select = function (item, clevel) {

                    if (ini) {
                        return;
                    }

                    if (clevel != level) {

                        for (var i = clevel + 1; i < 10; i++) {
                            var doc = $("#" + id + "_" + i);
                            if (doc.length > 0) {
                                doc.combobox("destroy");
                            }
                        }

                        if (item.value != "") {
                            load(item.value);
                        }

                        $("#" + id).val("");

                    }
                    else {

                        $("#" + id).val(item.value);

                    }

                }

                var load = function (locationid, fn, val) {
                    $.ajax({
                        url: "/PlatformAssembly/GetLocationList?parentid=" + locationid,
                        dataType: "json",
                        success: function (data) {
                            if (data.length > 0) {

                                var clevel = data[0].level;
                                var html = '<option value=""> --请选择-- </option>';
                                for (var i = 0; i < data.length; i++) {
                                    html += '<option value="' + data[i].id + '">' + data[i].text + '</option>';
                                }

                                $box.append("<select id='" + id + "_" + data[0].level + "' class='easyui-combobox' >" + html + "</select>");
                                var opr = {
                                    onSelect: function (item) {
                                        select(item, clevel);
                                    }
                                }
                                if (val) {
                                    opr.value = val
                                }

                                $("#" + id + "_" + data[0].level).combobox(opr);

                                if (fn) {
                                    fn(level);
                                }

                            }
                        }
                    });

                }

                if (value == "" || parseInt(value) <= 0) {
                    load(parentid, function () {
                        ini = false;
                    });
                } else {

                    $.ajax({
                        url: "/PlatformAssembly/GetLocationData?id=" + value,
                        dataType: "json",
                        success: function (data) {
                            var index = 0;
                            var fn = function () {

                                if (index < data.Data.length - 1) {
                                    load(data.Data[index], fn, data.Data[index + 1]);
                                    index++;
                                } else {
                                    ini = false;
                                }
                            }
                            fn();
                        }
                    });

                }




            });


            /*
                 *********  坐标拾取器  *********

                 isrequired：是否必选

            */

            array = new Array();
            if ($(this).hasClass("soon-coordinate")) {
                array.push(this);
            } else {
                $(this).find(".soon-coordinate").each(function () {
                    array.push(this);
                });
            }
            $.each(array, function () {

                var $source = $(this);
                var id = $source.attr("id") ? $source.attr("id") : ("i" + $.Guid());
                var name = $source.attr("name") ? $source.attr("name") : id;
                var value = $source.val() ? $source.val() : "";
                var className = $source.attr("class") ? $source.attr("class").replace("soon-location", "") : "";
                var required = ($source.attr("isrequired") == "false" || $source.attr("isrequired") == "0") ? 0 : 1;

                var html = '';
                html += '<iframe id="' + id + '_iframe" style="width:99%;height:160px;max-width:800px; border:1px solid #ddd;margin-bottom:6px"></iframe>';
                html += '<div id="' + id + '_info" style="margin-bottom:6px"></div>';
                html += '<a id="' + id + '_btn" class="easyui-linkbutton" ><i class="fa fa-map-marker"></i> 选择坐标</a>';
                html += '<a id="' + id + '_clear_btn" class="easyui-linkbutton" style="margin-left:5px"><i class="fa fa-eraser"></i> 清除选择</a>'
                html += '<input id="' + id + '" name="' + name + '" type="text"  value="' + value + '"  ' + (required == 1 ? ' class="easyui-validatebox" data-options="required:true,missingMessage:\'请选择坐标\'" ' : '') + ' style="height:0px; width:20px; border:none; overflow:hidden; line-height:0; " />';

                $(this).before(html);
                $(this).remove();

                if (value != "") {
                    $("#" + id + "_iframe").attr("src", "/PlatformAssembly/Coordinate?val=" + encodeURIComponent(value));
                    var obj = JSON.parse(value);
                    var data = "<strong>经度：</strong><span style='margin-right:8px;'>" + obj.lng + "</span>";
                    data += "<strong>纬度：</strong><span style='margin-right:8px;'>" + obj.lat + "</span>";
                    data += "<strong>缩放：</strong><span style='margin-right:8px;'>" + obj.zoom + "</span>";
                    data += "<strong>地址：</strong><span>" + obj.adr + "</span>";

                    $("#" + id + "_info").html(data);

                } else {
                    $("#" + id + "_iframe").hide();
                    $("#" + id + "_info").hide();
                    $("#" + id + "_clear_btn").hide();
                }

                $("#" + id + "_btn").click(function () {
                    var openid = soon.open({
                        id: "open_" + id,
                        url: '/PlatformAssembly/Coordinate?id=' + id + '&val=' + encodeURIComponent($("#" + id).val()),
                        width: "1000px",
                        height: "80%",
                        title: "设置坐标点",
                        iframe: true
                    });
                });

                $("#" + id + "_clear_btn").click(function () {
                    $("#" + id + "_iframe").hide();
                    $("#" + id + "_info").hide();
                    $("#" + id + "_clear_btn").hide();
                    $("#" + id).val("");
                });

            });


            /*
                 *********  多项选择器  *********

                 isrequired：是否必选
                 ismultiple:是否多选

            */

            array = new Array();
            if ($(this).hasClass("soon-selection")) {
                array.push(this);
            } else {
                $(this).find(".soon-selection").each(function () {
                    array.push(this);
                });
            }
            $.each(array, function () {

                var $source = $(this);
                var id = $source.attr("id") ? $source.attr("id") : ("i" + $.Guid());
                var name = $source.attr("name") ? $source.attr("name") : id;
                var value = $source.attr("value") ? $source.attr("value") : "";
                var className = $source.attr("class") ? $source.attr("class").replace("soon-location", "") : "";
                var required = ($source.attr("isrequired") == "false" || $source.attr("isrequired") == "0") ? 0 : 1;
                var multiple = ($source.attr("ismultiple") == "false" || $source.attr("ismultiple") == "0") ? 0 : 1;

                var html = '';
                html += ' <div class="soon-assembly-selection" id="' + id + '_box"> ';

                if (multiple == 1) {
                    html += '<label class="all">' +
                                '<input type="checkbox" />' +
                                '<span>全选</span>' +
                            '</label>';
                    html += '</br>';
                }

                var valueItem = value.split(',');
                $source.find("option").each(function () {

                    var selected = false;
                    for (item in valueItem) {

                        if (valueItem[item] == $(this).attr("value")) {
                            selected = true;
                        }
                    }
                    html += '<label class="item ' + (selected == true ? 'checked' : "") + '">' +
                                '<input type="' + (multiple == 1 ? "checkbox" : "radio") + '" ' + (selected == true ? 'checked="checked"' : "") + '  name="' + id + '_name" value="' + $(this).attr("value") + '"/>' +
                                '<span>' + $(this).html() + '</span>' +
                            '</label>';
                });
                html += '<input id="' + id + '" name="' + name + '" type="text"  value="' + value + '"  ' + (required == 1 ? ' class="easyui-validatebox" data-options="required:true,missingMessage:\'该项必须选择\'" ' : '') + ' style="height:0px; width:20px; border:none; overflow:hidden; line-height:0; " />';
                html += '</div>';

                $(this).before(html);
                $(this).remove();

                $("#" + id + "_box .all").click(function () {

                    if ($(this).find("input").is(':checked')) {
                        $("#" + id + "_box .item input").prop("checked", true);
                        $("#" + id + "_box .item").addClass("checked");
                        $("#" + id + "_box .all").addClass("checked");
                        var val = "";
                        $("#" + id + "_box .item input").each(function () {
                            val += (val == "" ? "" : ",") + $(this).attr("value");
                        });
                        $("#" + id).val(val);
                    } else {
                        $("#" + id + "_box .item input").prop("checked", false);
                        $("#" + id + "_box .item").removeClass("checked");
                        $("#" + id + "_box .all").removeClass("checked");
                        $("#" + id).val("");
                    }
                });

                $("#" + id + "_box .item").click(function () {

                    if (multiple == 1) {
                        $(this).removeClass("checked");
                        $("#" + id + "_box .all").removeClass("checked");
                    } else {
                        $("#" + id + "_box .item").removeClass("checked");
                    }


                    $("#" + id + "_box .all input").prop("checked", false);

                    var val = "";
                    $("#" + id + "_box .item input").each(function () {
                        if ($(this).is(':checked')) {
                            val += (val == "" ? "" : ",") + $(this).attr("value");
                            $(this).parent().addClass("checked");
                        }
                    });
                    $("#" + id).val(val);
                });

            });



            /*
                 *********  电子签名  *********

                 isrequired：是否必选
                 readOnly:是否只读

            */

            array = new Array();
            if ($(this).hasClass("soon-assembly-sign")) {
                array.push(this);
            } else {
                $(this).find(".soon-assembly-sign").each(function () {
                    array.push(this);
                });
            }
            $.each(array, function () {

                var $source = $(this);
                var id = $source.attr("id") ? $source.attr("id") : ("i" + $.Guid());
                var name = $source.attr("name") ? $source.attr("name") : id;
                var value = $source.attr("value") ? $source.attr("value") : "";
                var className = $source.attr("class") ? $source.attr("class").replace("soon-location", "") : "";
                var required = ($source.attr("isrequired") == "false" || $source.attr("isrequired") == "0") ? 0 : 1;
                var readOnly = ($source.attr("isReadOnly") == "false" || $source.attr("isReadOnly") == "0") ? 0 : 1;
                var path = $source.attr("path");

                var html = '';
                html += ' <div class="soon-assembly-sign-container" id="' + id + '_box"> ';
                if (value != "") {
                    html += ' <img src="" style="display:block;"> ';
                    html += ' <span style="display:none;">签名区域</span> ';
                } else {
                    html += ' <img src=""> ';
                    html += ' <span>签名区域</span> ';
                }
                html += '<input id="' + id + '" name="' + name + '" type="text"  value="' + value + '"  ' + (required == 1 ? ' class="easyui-validatebox" data-options="required:true,missingMessage:\'您必须签名才能继续\'" ' : '') + ' style="height:0px; width:20px; border:none; overflow:hidden; line-height:0; " />';
                html += '</div>';
                $(this).before(html);
                $(this).remove();

                if (readOnly == 0) {
                    $("#" + id + "_box").click(function () {
                        $.soon.service({
                            url: '/sign',
                            success: function (data) {
                                if (data.State) {
                                    $.soon.ajax({
                                        url: "/PlatformAssembly/UploadImageSubmit",
                                        data: { data: data.Data, path: path, encrypt: 1, name: "Sign.jpg" },
                                        success: function (res) {
                                            if (res.State) {
                                                $("#" + id).val(res.Data);
                                                getFileURL(res.Data);
                                            } else {
                                                layer.msg(res.Message);
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    });
                    testService = true;
                }

                var getFileURL = function (val) {
                    $.ajax({
                        url: "/PlatformAssembly/GetFileURL",
                        data: { val: val },
                        dataType: "text",
                        success: function (data) {
                            $img = $("#" + id + "_box img").attr("src", data);
                            $("#" + id + "_box img").show();
                            $("#" + id + "_box span").hide();
                        }
                    });
                }

                if (value != "") {
                    getFileURL(value);
                }

            });

            if (testService == true) {
                $.soon.service();
            }

            $.parser.parse($(this));

        }

    });

    $.extend({
        soon: soon,
    });

    if ($.fn.form) {
        $.extend($.fn.form.methods, {
            ini: function (doc, par) {

                $(doc).form({
                    url: par.url,
                    onSubmit: function () {
                        var validate = $(this).form('validate');
                        if (validate) {
                            soon.loading("正在处理");
                        } else {
                            layer.msg("请正确填写红色部分信息");
                        }
                        return validate;
                    },
                    success: function (data) {
                        soon.loading(false);
                        var r = $.parseJSON(data);
                        par.success(r);
                    },
                    onLoadError: function (e) {
                        soon.loading(false);
                        layer.msg("处理失败，服务器繁忙");
                        console.log(e);
                    }
                });
                if (par.data) {
                    $(doc).form('load', par.data);
                }


            }
        });
    }

})(jQuery);


$(function () {

    if (!window.mqservice) {
        return
    }

    var mq = {}
    mq.option = {
        onopen: function () {

            if (mq.connectCount > 1) {
                console.log("与服务器重新连接");
            } else {
                console.log("服务器连接成功");
            }

            mq.connectCount = 0;

            //加载提示信息
            mq.ws.send(JSON.stringify({ Action: "Soon.Platform.Tips", Data: { Type: "Message" } }));

            mq.status = 1;

            //加载会话
            if (im.chatid > 0) {
                im.chat(im.chatid, 0);
            }

        },
        onmessage: function (evt) {

            var data = JSON.parse(evt.data);

            console.log(data);

            if (data.Action == "Soon.Platform.Tips") {
                mq.tips.handle(data.Data);
            }
            else if (data.Action == "Soon.Platform.Message") {
                mq.im.handle(data.Data);
            }

        },
        onclose: function (evt) {
            console.log(evt);
            console.log("连接被关闭，准备重新连接");
            mq.connect();
        },
        onerror: function (evt) {
            console.log(evt);
            console.log("连接出现错误");
        }
    };
    mq.status = 0;
    mq.reconnect = true;
    mq.connectCount = 0;
    mq.connect = function () {

        mq.status = 0;
        if (mq.reconnect) {

            if (!mq.connectCount) {
                mq.connectCount = 0;
            }

            if (mq.connectCount >= 30) {

                return;

                mq.reconnect = false;
                layer.open({
                    title: "连接丢失",
                    icon: 2,
                    content: "与服务器失去连接，请刷新重试",
                    btn: ["确认"],
                    closeBtn: false,
                    yes: function (index) {
                        layer.close(index);
                        top.window.location.reload();
                    }
                });

                return;

            }

            setTimeout(function () {

                if (mq.connectCount > 0) {
                    console.log("与服务器失去连接,第" + mq.connectCount + "次重新连接");
                }

                var ws = new WebSocket(window.mqservice);
                ws.onopen = mq.option.onopen;
                ws.onmessage = mq.option.onmessage;
                ws.onclose = mq.option.onclose;
                ws.onerror = mq.option.onerror;
                mq.ws = ws;
                mq.connectCount++;

            }, mq.connectCount == 0 ? 0 : 10000);

        }



    }
    mq.connect();

    var tips = {
        handle: function (data) {
            switch (data.Type) {
                case "Message":
                    tips.message(data);
                    break;
                case "Timeout":
                    tips.timeout(data.Message);
                    break;
                case "Session":
                    tips.session(data.Second);
                    break;
            }
        },
        message: function (data) {

            tips.IsNotice = data.IsNotice;
            tips.IsMessage = data.IsMessage;
            tips.IsTask = data.IsTask;

            if (data.IsNotice == 1) {
                $(".main-header-nav a").eq(0).append("<b></b>");
                tips.notification("Soon Platform", "您有未读系统通知，请注意查看");
                im.notice = 1;
            } else {
                $(".main-header-nav a").eq(0).find("b").remove();
                im.notice = 0;
            }

            if (data.IsMessage == 1) {
                $(".main-header-nav a").eq(1).append("<b></b>");
                tips.notification("Soon Platform", "您有未读消息，请注意查看");
            } else {
                $(".main-header-nav a").eq(1).find("b").remove();
            }

            if (data.IsTask == 1) {
                $(".main-header-nav a").eq(3).append("<b></b>")
            } else {
                $(".main-header-nav a").eq(3).find("b").remove();
            }

        },
        timeout: function (msg) {
            layer.open({
                title: "登录失效",
                icon: 2,
                content: msg,
                btn: ["确认"],
                closeBtn: false,
                yes: function (index) {
                    layer.close(index);
                    top.window.location = "/Platform/Quit";
                }
            });
            mq.reconnect = false;
        },
        session: function (second) {

            if (!tips.session_second) {
                var loginTimeoutInterval = setInterval(function () {
                    tips.session_second--;
                    if (tips.session_second <= 0) {
                        clearInterval(loginTimeoutInterval);
                        tips.timeout("您的登录信息已超时，请重新登录");
                    }
                }, 1000);
            }

            tips.session_second = second;

        },
        heart: setInterval(function () {
            //心跳函数
            if (tips.IsMessage == 1) {

                if (tips.heart_message == 1) {
                    tips.heart_message = 0;
                    $(".main-header-nav-msg i").eq(0).animate({
                        opacity: .1
                    }, 100);
                } else {
                    tips.heart_message = 1;
                    $(".main-header-nav-msg  i").eq(0).animate({
                        opacity: 1
                    }, 100);
                }

            } else if (tips.heart_message == 0) {
                $(".main-header-nav-msg  i").eq(0).animate({
                    opacity: 1
                }, 100);
            }


            if (tips.IsNotice == 1) {

                if (tips.heart_notice == 1) {
                    tips.heart_notice = 0;
                    $(".main-header-nav-notice i").eq(0).animate({
                        opacity: .1
                    }, 100);
                } else {
                    tips.heart_notice = 1;
                    $(".main-header-nav-notice  i").eq(0).animate({
                        opacity: 1
                    }, 100);
                }

            } else if (tips.heart_notice == 0) {
                $(".main-header-nav-notice  i").eq(0).animate({
                    opacity: 1
                }, 100);
            }

        }, 500),
        notification: function (title, content) {
            if (Notification) {
                Notification.requestPermission(function (perm) {
                    if (perm == "granted") {
                        var notification = new Notification(title, {
                            dir: "auto",
                            lang: "hi",
                            tag: "tips",
                            icon: "/platform/resource/im/img/notification_bell.png",
                            body: content
                        });
                    }
                });
            }
        }
    }
    if (Notification) {
        Notification.requestPermission();
    }

    mq.tips = tips;


    var im = {
        chatid: 0,
        option: {},
        data: null,
        limitFileSize: function (file, limitSize) {
            /* 限制文件大小，返回 boolean
             * file:文件对象
             * limiteSize:限制大小---例如："50MB"
             * */
            var arr = ["KB", "MB", "GB"]
            var limit = limitSize.toUpperCase();
            var limitNum = 0;
            for (var i = 0; i < arr.length; i++) {
                var leval = limit.indexOf(arr[i]);
                if (leval > -1) {
                    limitNum = parseInt(limit.substr(0, leval)) * Math.pow(1024, (i + 1))
                    break
                }
            }
            if (file.size > limitNum) {
                return false
            }
            return true
        },
        imageViewer: function (e) {
            setTimeout(function () {
                $(".im-chat-content-img").find("img").viewer({ zIndex: 99999, title: false, navbar: false });
            }, 100);
        },
        handle: function (data) {
            if (data.Types == "Message") {
                im.msg(data);
            }
        },
        dialog: function (option) {

            option = $.extend({
                width: "900px",
                height: "600px",
                uid: 0,
                chatid: 0,
            }, option || {});

            if (im.chatid > 0) {
                //如果聊天窗口打开，直接载入，无需初始化
                im.option.chatid = option.chatid;
                im.option.uid = option.uid
                im.chat(option.chatid, option.uid);
                return;
            }

            im.option = option;

            //载入联系人列表
            soon.ajax({
                url: "/PlatformMessage/Contact",
                success: function (data) {

                    im.data = data.Data;
                    im.data.tab = 1;
                    im.data.chat = null;
                    im.data.content = "";
                    im.data.searchOrganize = "";
                    im.data.searchRecent = "";

                    //弹出对话框
                    var inx = layer.open({
                        title: false,
                        area: [option.width, option.height],
                        type: 1,
                        content: im.template.dialog,
                        zIndex: 9999,
                        shade: false,
                        closeBtn: false,
                        move: ".im-dialog-move",
                        end: function () {
                            clearInterval(option.heart);
                        }
                    });

                    option.id = "#layui-layer" + inx;
                    option.heart = setInterval(function () {
                        //心跳函数
                        if (im.notice == 1) {

                            if (im.notice_show == 1) {
                                im.notice_show = 0;
                                $(".im-panel-footer .layui-icon").eq(0).animate({
                                    opacity: .1
                                }, 100);
                            } else {
                                im.notice_show = 1;
                                $(".im-panel-footer .layui-icon").eq(0).animate({
                                    opacity: 1
                                }, 100);
                            }

                        } else if (im.notice_show == 0) {
                            $(".im-panel-footer .layui-icon").eq(0).animate({
                                opacity: 1
                            }, 100);
                        }

                    }, 400);

                    setTimeout(function () {

                        $(option.id).addClass("im-box");


                        Vue.component('imtree', {
                            template: '#im_tree',
                            props: {
                                model: Object,
                                level: Object
                            },
                            methods: {
                                welcome: function (model) {
                                    this.$emit('welcome', model)
                                }
                            }
                        });

                        if (option.chatid > -1 && option.uid > -1) {
                            //载入聊天窗口·
                            im.chat(option.chatid, option.uid);
                        }

                        var app = new Vue({
                            el: option.id + " .im-vue",
                            data: im.data,
                            computed: {
                                computedOrganize: function () {

                                    var thls = this;

                                    if (thls.searchOrganize == "") {
                                        return thls.contact;
                                    } else {

                                        var arr = new Array();
                                        var filter = function (filterList, arrList, parentSearch) {

                                            for (var i = 0; i < filterList.length; i++) {

                                                var item = filterList[i];

                                                var subArr = new Array();
                                                var search = parentSearch ? true : false;
                                                if (search == false) {
                                                    search = (item.name.indexOf(thls.searchOrganize) > -1);
                                                }

                                                if (item.hasOwnProperty("children")) {
                                                    filter(item.children, subArr, search);
                                                }
                                                if (subArr.length > 0 || search) {

                                                    var data = JSON.parse(JSON.stringify(item));
                                                    if (subArr.length > 0) {
                                                        data.children = subArr;
                                                    } else {
                                                        if (data.hasOwnProperty("children")) {
                                                            delete data.children;
                                                        }
                                                    }
                                                    arrList.push(data);
                                                }
                                            }

                                        }

                                        filter(thls.contact, arr, false);
                                        return arr;
                                    }
                                },
                                computedRecent: function () {

                                    var thls = this;
                                    if (thls.searchRecent == "") {
                                        return thls.recent;
                                    } else {
                                        var arr = new Array();
                                        for (var i = 0; i < thls.recent.length; i++) {
                                            var item = thls.recent[i];
                                            if ((item.name.indexOf(thls.searchRecent) > -1)) {
                                                arr.push(item);
                                            }
                                        }
                                        return arr;
                                    }

                                }
                            },
                            methods: {
                                close: function () {
                                    im.chatid = 0;
                                    layer.close(inx);
                                },
                                about: function () {

                                    var inx = layer.open({
                                        title: "关于IM",
                                        area: ["200px", "130px"],
                                        type: 1,
                                        content: im.template.about,
                                        shade: false,
                                    });

                                },
                                notice: function () {
                                    option.chatid = 0;
                                    option.uid = 0;
                                    im.chat(0, 0);
                                },
                                open: function (data) {
                                    if (data.type == 2 || data.type == 1) {
                                        option.chatid = 0;
                                        option.uid = data.uid;
                                        im.chat(option.chatid, option.uid);
                                    } else if (data.type == 3) {
                                        option.chatid = data.chatid;
                                        option.uid = 0;
                                        im.chat(option.chatid, option.uid);
                                    }
                                },
                                send: function () {
                                    if (app.content != "") {

                                        $.ajax({
                                            url: "/PlatformMessage/SendText",
                                            data: { content: app.content, chatid: im.chatid },
                                            dataType: "json",
                                            success: function (data) {
                                                if (!data.State) {
                                                    app.chat.msg.push({
                                                        content: data.Message,
                                                        type: 0
                                                    });
                                                }
                                            }, error: function () {
                                                app.chat.msg.push({
                                                    content: "消息发送失败",
                                                    type: 0
                                                });
                                            }
                                        });

                                        app.chat.msg.push({
                                            content: app.content,
                                            date: new Date().format("MM/dd HH:mm:ss"),
                                            type: 1,
                                            source: "from"
                                        });

                                        setTimeout(function () {
                                            app.content = "";
                                        }, 100);
                                        im.textareaFocus();
                                    }
                                },
                                sendKeydown: function (e) {
                                    if (!e) e = window.event;
                                    if ((e.keyCode || e.which) == 13) {
                                        app.send();
                                    }
                                },
                                image: function (doc) {

                                    if (doc.target.files.length == 0) {
                                        return;
                                    } else if (!im.limitFileSize(doc.target.files[0], "20MB")) {
                                        layer.msg("文件过大，最多允许发送20MB以内的文件");
                                        doc.target.value = "";
                                        return;
                                    }

                                    //发送图片
                                    var form = new FormData();
                                    form.append('file', doc.target.files[0]);
                                    soon.loading("正在发送图片");
                                    fetch('/PlatformMessage/SendImage?chatid=' + im.chatid, {
                                        method: 'POST',
                                        credentials: 'include',
                                        body: form
                                    }).then(function (response) {
                                        if (response.status >= 200 && response.status < 300) {
                                            return response;
                                        }
                                        else {
                                            var error = new Error(response.statusText);
                                            error.response = response;
                                            throw error;
                                        }
                                    }).then(function (resp) {
                                        return resp.json();
                                    }).then(function (data) {
                                        doc.target.value = "";
                                        soon.loading(false);
                                        if (data.State) {

                                            app.chat.msg.push({
                                                content: "[图片文件]",
                                                type: 2,
                                                url: data.Data,
                                                source: "from"
                                            });
                                            im.imageViewer();
                                        } else {
                                            app.chat.msg.push({
                                                content: data.Message,
                                                type: 0
                                            });
                                        }
                                        im.textareaFocus();
                                    }).catch(function (e) {
                                        doc.target.value = "";
                                        soon.loading(false);
                                        app.chat.msg.push({
                                            content: "图片发送失败",
                                            type: 0
                                        });
                                        im.textareaFocus();
                                    });
                                },
                                files: function (doc) {

                                    if (doc.target.files.length == 0) {
                                        return;
                                    } else if (!im.limitFileSize(doc.target.files[0], "20MB")) {
                                        layer.msg("文件过大，最多允许发送20MB以内的文件");
                                        doc.target.value = "";
                                        return;
                                    }

                                    //发送文件
                                    var form = new FormData();
                                    form.append('file', doc.target.files[0]);
                                    soon.loading("正在发送文件");
                                    fetch('/PlatformMessage/SendFiles?chatid=' + im.chatid, {
                                        method: 'POST',
                                        credentials: 'include',
                                        body: form
                                    }).then(function (response) {
                                        if (response.status >= 200 && response.status < 300) {
                                            return response;
                                        }
                                        else {
                                            var error = new Error(response.statusText);
                                            error.response = response;
                                            throw error;
                                        }
                                    }).then(function (resp) {
                                        return resp.json();
                                    }).then(function (data) {

                                        soon.loading(false);
                                        if (data.State) {

                                            app.chat.msg.push({
                                                content: "[文件“" + doc.target.files[0].name + "”]",
                                                type: 3,
                                                url: data.Data,
                                                source: "from"
                                            });
                                            im.imageViewer();
                                        } else {
                                            app.chat.msg.push({
                                                content: data.Message,
                                                type: 0
                                            });
                                        }
                                        im.textareaFocus();
                                        doc.target.value = "";
                                    }).catch(function (e) {
                                        soon.loading(false);
                                        app.chat.msg.push({
                                            content: "文件发送失败",
                                            type: 0
                                        });
                                        im.textareaFocus();
                                        doc.target.value = "";
                                    });
                                },
                                face: function (e) {

                                    var faceinx = layer.open({
                                        title: false,
                                        area: ["400px", "200px"],
                                        closeBtn: false,
                                        offset: [(e.clientY - 210) + "px", e.clientX + "px"],
                                        type: 1,
                                        content: im.template.face,
                                        zIndex: 9999,
                                        shade: [0.01, "#fff"],
                                        shadeClose: true,
                                        resize: false,
                                    });

                                    $("#layui-layer" + faceinx + " .im-face ul li").click(function () {
                                        app.content = app.content + " face" + $(this).attr("title");
                                        layer.close(faceinx);
                                        $(option.id + " textarea").focus();
                                    });

                                },
                                faceConvert: function (content) {
                                    for (var i = 0; i < im.face.length; i++) {
                                        content = content.replace(im.face[i].name, im.face[i].img);
                                    }
                                    return content;
                                },
                                history: function () {

                                    var historyInx = layer.open({
                                        title: "和“" + im.data.chat.to.name + "”的聊天记录",
                                        area: ["600px", "99%"],
                                        closeBtn: 1,
                                        offset: 'r',
                                        type: 1,
                                        content: im.template.history,
                                        shade: false,
                                        resize: false,
                                    });

                                    var historyApp = new Vue({
                                        el: "#layui-layer" + historyInx + " .layui-layer-content",
                                        data: {
                                            page: 1,
                                            end: false,
                                            loading: false,
                                            chat: {
                                                msg: [],
                                                from: im.data.chat.from,
                                                to: im.data.chat.to
                                            }
                                        }, methods: {
                                            scrollEvent: function (e) {

                                                var clientHeight = $("#layui-layer" + historyInx + " .layui-layer-content").height();
                                                var scrollTop = $(e.target).scrollTop();
                                                var scrollHeight = $(".im-history-scrol").height();
                                                if (scrollTop + clientHeight + 40 >= scrollHeight) {
                                                    historyApp.load();
                                                }

                                            },
                                            load: function () {

                                                if (historyApp.end == false && historyApp.loading == false) {
                                                    historyApp.loading = true;
                                                    soon.ajax({
                                                        url: "/PlatformMessage/History",
                                                        data: { chatid: im.chatid, page: historyApp.page },
                                                        success: function (data) {
                                                            historyApp.loading = false;
                                                            if (data.State) {
                                                                for (var i = 0; i < data.Data.List.length; i++) {
                                                                    historyApp.chat.msg.push(data.Data.List[i]);
                                                                }
                                                                if (data.Data.End) {
                                                                    historyApp.end = true;
                                                                } else {
                                                                    historyApp.page++;
                                                                }

                                                                im.imageViewer();


                                                            } else {
                                                                layer.msg(data.Message);
                                                            }
                                                        }, error: function () {
                                                            historyApp.loading = false;
                                                        }
                                                    });
                                                }
                                            },
                                            faceConvert: function (content) {
                                                for (var i = 0; i < im.face.length; i++) {
                                                    content = content.replace(im.face[i].name, im.face[i].img);
                                                }
                                                return content;
                                            },

                                        }
                                    });

                                    historyApp.load();



                                },
                                audio: function () {

                                },
                                video: function () {

                                },
                            }
                        });

                        $(".im-dialog").css("display", "flex");

                        setTimeout(function () {
                            $(".im-dialog-move .layui-layer-close").click(function () {
                                app.close(inx);
                            });
                        }, 100);




                    }, 100);


                }
            })


        },
        open: function () {
            option = $.extend({
                width: "600px",
                height: "500px",
                uid: 0
            }, option || {});

            soon.loading();
            soon.ajax({
                url: "/PlatformMessage/Chat?uid=" + option.uid,
                success: function (data) {
                    soon.loading(false);
                    option.data = data.Data;
                    if (data.State) {
                        $.im.chat(option);
                    } else {
                        layer.msg(data.Message);
                    }
                }, error: function () {
                    soon.loading(false);
                }
            });
        },
        textareaFocus: function () {

            var temp = setTimeout(function () {
                clearTimeout(temp);
                $(im.option.id + " .im-chat-content").scrollTop($(im.option.id + " .im-chat-content").prop("scrollHeight"), 400);
                $(".im-chat-textarea textarea").focus();
            }, 200);

        },
        chat: function (chatid, uid) {

            //载入聊天信息
            soon.ajax({
                url: "/PlatformMessage/Chat?chatid=" + chatid + "&uid=" + uid,
                errroMsg: "聊天信息载入失败",
                success: function (data) {
                    if (data.State) {
                        im.data.chat = data.Data;
                        im.chatid = data.Data.chatid;
                        im.textareaFocus();
                        im.imageViewer();
                    } else {
                        layer.msg(data.Message)
                    }
                }
            });
        },
        msg: function (data) {
            if (data.ChatID != im.chatid) {
                $.ajax({ url: "/PlatformMessage/SendFail?chatid=" + data.ChatID });
            } else {
                im.data.chat.msg.push(data.Message);
                im.textareaFocus();
                im.imageViewer();
            }
        },
        template: {
            load: function () {

                $.ajax({
                    dataType: "text",
                    url: "/platform/resource/im/template/history.html",
                    success: function (data) {
                        im.template.history = data;
                    }
                });

                $.ajax({
                    dataType: "text",
                    url: "/platform/resource/im/template/about.html",
                    success: function (data) {
                        im.template.about = data;
                    }
                });

                $.ajax({
                    dataType: "text",
                    url: "/platform/resource/im/template/dialog.html",
                    success: function (data) {
                        im.template.dialog = data;
                    }
                });

                $.ajax({
                    dataType: "text",
                    url: "/platform/resource/im/template/face.html",
                    success: function (data) {
                        im.template.face = data;
                        im.face = [];
                        var doc = $(data);
                        doc.find("li").each(function () {
                            im.face.push({
                                img: " <img src='" + $(this).find("img").attr("src") + "' />",
                                name: new RegExp("face" + $(this).attr("title").replace("[", "\\[").replace("]", "\\]"), "g")
                            });
                        });
                    }
                });
            }
        }
    }
    im.template.load();
    mq.im = im;

    $.mq = mq;



});

